<?php

namespace Winter\Blog\Components;

use Cms\Classes\ComponentBase;
use Cms\Classes\Page;
use Illuminate\Support\Collection;
use Winter\Blog\Models\Banner as BlogBanner;

class Banner extends ComponentBase
{
    /**
     * A collection of categories to display
     */
    public $banners ;

    /**
     * Reference to the page name for linking to categories.
     */
    public ?string $categoryPage = '';

    /**
     * Reference to the current category slug.
     */
    public ?string $currentCategorySlug = '';

    public function componentDetails(): array
    {
        return [
            'name'        => 'winter.blog::lang.settings.banners_title',
            'description' => 'winter.blog::lang.settings.banners_description'
        ];
    }

    public function defineProperties(): array
    {
        return [
            
        ];
    }

    public function getCategoryPageOptions()
    {
        return Page::sortBy('baseFileName')->lists('baseFileName', 'baseFileName');
    }

    public function onRun()
    {
        $this->currentCategorySlug = $this->page['currentCategorySlug'] = $this->property('slug');
        $this->categoryPage = $this->page['categoryPage'] = $this->property('categoryPage');
        $this->categories = $this->page['categories'] = $this->loadCategories();
    }

    /**
     * Load all categories or, depending on the <displayEmpty> option, only those that have blog posts
     */
    protected function loadBanners(): Collection
    {
        $query = BlogBanner::withCount(['posts_count'])
            ->orderBy('created_at', 'desc');


        $query->limit(5);

        return $query->get()->each(fn ($tag) => $tag->setUrl($this->tagPage, $this->controller));
    }

    /**
     * Sets the URL on each category according to the defined category page
     */
    protected function linkCategories(Collection $categories): Collection
    {
        return $categories->each(function ($category) {
            $category->setUrl($this->categoryPage, $this->controller);

            if ($category->children) {
                $this->linkCategories($category->children);
            }
        });
    }
}
